<template>
  <!-- 写日报 -->
  <el-dialog
    v-model="props.modelValue"
    width="1200px"
    :show-close="false"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4
          :id="titleId"
          :class="titleClass"
        >
          {{ dialogTitle }}
        </h4>
        <img
          src="@/assets/img/icon_guanbi.png"
          @click="close"
          class="close"
        />
      </div>
    </template>

    <div class="main">
      <el-form
        ref="formEl"
        :model="formData"
        :rules="rules"
        :disabled="isDisabled"
        label-width="160px"
      >
        <div class="top">
          <el-form-item
            prop="shipId"
            :label="t('daily.p2')"
            class="border"
          >
            <el-select-v2
              v-model="formData.shipId"
              :options="shipOptions"
              placeholder=" "
              clearable
              filterable
              @change="shipChange"
              class="big"
            />
          </el-form-item>

          <el-form-item
            prop="shipyardId"
            :label="t('daily.p4')"
            class="border"
          >
            <el-select-v2
              v-model="formData.shipyardId"
              :options="shipyarOptions"
              placeholder=" "
              clearable
              filterable
              @change="shipyardChange"
              class="big"
            />
          </el-form-item>
        </div>

        <div class="grid">
          <el-form-item
            prop="arrivalDate"
            :label="t('daily.p12')"
            class="border"
          >
            <el-date-picker
              v-model="dateTime.arrivalDate"
              type="date"
              @change="dateChange($event, 'arrivalDate')"
            />
          </el-form-item>

          <el-form-item
            prop="etd"
            :label="t('daily.p13')"
            class="border"
          >
            <el-date-picker
              v-model="dateTime.etd"
              type="date"
              @change="dateChange($event, 'etd')"
            />
          </el-form-item>
        </div>

        <div class="grid">
          <el-form-item
            prop="weather"
            :label="t('daily.p16')"
            class="border"
          >
            <el-select v-model="formData.weather" class="wp-100" clearable filterable placeholder=" ">
                <el-option v-for="item in dictData['weather']" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
          </el-form-item>

          <el-form-item
            prop="pic"
            :label="t('daily.p15')"
            class="border"
          >
            <el-input
              v-model="formData.pic"
              disabled
            ></el-input>
          </el-form-item>
        </div>

        <div class="grid">
          <el-form-item
            prop="shipLocation"
            :label="t('daily.p6')"
            class="border"
          >
            <el-select
              v-model="formData.shipLocation"
              class="wp-100"
              placeholder=" "
               filterable
            >
              <el-option
                v-for="item in positionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            prop="reportingDate"
            :label="t('daily.p14')"
            class="border"
          >
            <el-date-picker
              v-model="dateTime.reportingDate"
              type="date"
              @change="dateChange($event, 'reportingDate')"
            />
          </el-form-item>
        </div>

        <template v-if="['edit', 'add'].includes(props.type)">
          <el-form-item
            prop="projectType"
            :label="t('daily.p19')"
            class=" mt-3"
          >
            <div class="pro-list flexsc">
              <div
                :class="['item', 'mr-1', { active: activePro === item.dictValue }]"
                v-for="item in dictData['project_type']"
                :key="item.dictValue"
                @click="changeProType(item)"
              >
                {{ item.dictLabel }}
              </div>
            </div>
          </el-form-item>

          <el-form-item :label="t('daily.p17')">
            <el-select-v2
              v-model="maintenanceItem"
              :options="dailyProjectConfigList"
              placeholder=" "
              clearable
              filterable
              @change="maintenanceItemChange"
            />
          </el-form-item>
        </template>

        <el-form-item
          prop="illustrate"
          :label="t('daily.p18')"
        >
          <WangEditor
            v-if="!isDisabled"
            ref="wangEditorRef"
            :valueHtml="formData.illustrate"
          />
          <div
            v-else
            v-html="formData.illustrate"
          ></div>
        </el-form-item>

        <el-form-item prop="aaa">
          <Uploads
            ref="UploadsRef"
            listType="picture-card"
            :readonly="isDisabled"
            :tip="t('daily.p11')"
            :limit="20"
            @change="fileChange"
          />
        </el-form-item>
      </el-form>
    </div>

    <template
      #footer
      v-if="!isDisabled"
    >
      <div class="dialog-footer flexcc">
        <el-button
          color="#252628"
          plain
          @click="cancel"
        >
          {{ t('cancelText') }}
        </el-button>
        <el-button
          type="primary"
          color="#252628"
          @click="confirm"
        >
          {{ t('confirmText') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, onBeforeMount, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import useDict from '@/hooks/useDict'
import { getShippingListApi, dailyProjectConfigListApi, getCustomerListApi, dailyAddApi, dailyEditApi, dailyDetailApi, listDockRepairWinningTheBidApi, getNewMaintenanceDailyApi } from '@/service/daily'
import { uploads } from '@/service/common'
import Uploads from '@/components/Uploads.vue'
import WangEditor from '@/components/WangEditor.vue'
import useLogin from '@/stores/login'
import moment from 'moment'

const storeLogin = useLogin()

const { t, locale } = useI18n()
const { dictData, getDictData } = useDict()

onBeforeMount(() => {
  init()
})

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'add'
  },
  editId: {
    type: [String, Number],
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'getList'])

const handleClose = () => {
  emit('update:modelValue')
}

const isDisabled = ref(props.type === 'detail')
const dialogTitle = computed(() => {
  const obj = {
    add: t('daily.t1'),
    edit: t('daily.t2'),
    detail: t('daily.t3')
  }
  return obj[props.type]
})

// 船舶名称
const shipOptions = ref([])
const getShippingList = () => {
  getShippingListApi().then(({ data }) => {
    shipOptions.value = data.map((r) => {
      return {
        value: r.id,
        label: r.shippingName
      }
    })
  })
}
const shipChange = (val) => {
  formData.value.shipName = shipOptions.value.find((item) => item.value === val).label
}

// 修船厂
const shipyarOptions = ref([])
const getlistDockRepairWinningTheBid = () => {
  listDockRepairWinningTheBidApi().then(({ data }) => {
    const arr = data.filter((item) => item !== null)

    const map = new Map()
    for (let item of arr) {
      map.set(item.id, item)
    }

    const list = [...map.values()]

    shipyarOptions.value = list.map((r) => {
      return {
        value: r.id,
        label: r.enterpriseName
      }
    })
  })
}
const shipyardChange = (val) => {
  formData.value.shipyardName = shipyarOptions.value.find((item) => item.value === val).label
}

// 船队经理
const customerList = ref([])
const getCustomerList = () => {
  getCustomerListApi().then(({ data }) => {
    customerList.value = data.map((r) => {
      return {
        value: r.id,
        label: r.userName
      }
    })
  })
}

// 维修项目
const activePro = ref(null)
const maintenanceItem = ref('')
const dailyProjectConfigList = ref([])
const getDailyProjectConfigList = (value) => {
  dailyProjectConfigListApi({ value }).then(({ data }) => {
    dailyProjectConfigList.value = data.map((r) => {
      return {
        value: r.content,
        label: r.projectName
      }
    })
  })
}
const changeProType = (item) => {
  maintenanceItem.value = ''
  activePro.value = item.dictValue
  getDailyProjectConfigList(item.dictValue)
}
const maintenanceItemChange = (val) => {
  formData.value.illustrate = wangEditorRef.value.getValueHtml() + val
}

const dateTime = ref({
  date: null
})
const dateChange = (val, key) => {
  formData.value[key] = val ? moment(val).unix() : null
}

// 表单
const wangEditorRef = ref() // 富文本编辑器ref
const formEl = ref(null)
const formData = ref({
  illustrate: ''
})
const rules = ref({})
const validator = {
  illustrate: (rule, value, callback) => {
    const empty = wangEditorRef.value.getIsEmpty()
    if (empty) {
      return callback(t('daily.r10'))
    }
    callback()
  }
}
const setRules = () => {
  rules.value = {
    shipId: [{ required: true, message: t('daily.r2'), trigger: 'change' }],
    shipyardId: [{ required: true, message: t('daily.r4'), trigger: 'change' }],
    arrivalDate: [{ required: true, message: t('daily.r3'), trigger: 'change' }],
    etd: [{ required: true, message: t('daily.r3'), trigger: 'change' }],
    reportingDate: [{ required: true, message: t('daily.r3'), trigger: 'change' }],
    pic: [{ required: true, message: t('daily.r11'), trigger: 'change' }],
    weather: [{ required: true, message: t('daily.r5'), trigger: 'change' }],
    shipLocation: [{ required: true, message: t('daily.r6'), trigger: 'change' }],
    illustrate: [{ required: true, validator: validator.illustrate, trigger: 'change' }]
  }
}
const setDefault = () => {
  const pic = storeLogin.userInfo.userName
  const picId = storeLogin.userInfo.id
  dateTime.value.reportingDate = moment().valueOf()
  dateChange(moment().valueOf(), 'reportingDate')

  // 带出上次的数据
  getNewMaintenanceDailyApi().then(({ data }) => {
    const { shipId, shipName, arrivalDate, etd } = data
    formData.value = {
      ...formData.value,
      pic,
      picId,
      shipId,
      shipName,
      arrivalDate,
      etd
    }
    dateTime.value.arrivalDate = arrivalDate ? arrivalDate * 1000 : null
    dateTime.value.etd = etd ? etd * 1000 : null
  })
}

// 文件列表
const fileList = ref([])
const fileChange = (val) => {
  fileList.value = val
}

// 组件实例
const UploadsRef = ref()

const handleUpload = (el, index) => {
  return new Promise((resolve, reject) => {
    const newList = fileList.value.filter((item) => item.raw)
    const oldList = fileList.value.filter((item) => !item.raw).map((item) => item.url)

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls }) => {
        const resultFile = urls.split(',')
        fileList.value = resultFile.map((item) => {
          return {
            name: item.slice(item.lastIndexOf('/') + 1),
            url: item
          }
        })
        el.setFileList(fileList.value)
        resolve([...oldList, ...resultFile])
      })
    } else {
      resolve(oldList)
    }
  })
}

// 取消
const cancel = () => {
  handleClose()
}

// 确定
const confirm = () => {
  if (!formEl.value) return

  formEl.value.validate(async (valid, fields) => {
    if (valid) {
      formData.value.illustrate = wangEditorRef.value.getValueHtml()
      const arr = await handleUpload(UploadsRef.value)
      formData.value.picture = arr?.length ? arr.join() : null

      const obj = {
        add: dailyAddApi,
        edit: dailyEditApi
      }

      obj[props.type](formData.value).then(({ msg }) => {
        ElMessage.success(msg)
        handleClose()
        emit('getList')
      })
    }
  })
}

// 详情
const getDetail = () => {
  dailyDetailApi(props.editId).then(({ data }) => {
    const { arrivalDate, etd, reportingDate, picture } = data
    dateTime.value = {
      arrivalDate: arrivalDate * 1000,
      etd: etd * 1000,
      reportingDate: reportingDate * 1000
    }

    const urlList = picture ? picture?.split(',') : []
    fileList.value = urlList.map((url) => {
      return {
        name: url.slice(url.lastIndexOf('/') + 1),
        url
      }
    })
    UploadsRef.value.setFileList(fileList.value)

    formData.value = data
  })
}

// 船舶位置
const positionOptions = ref([
  {
    label: t('daily.o1_1'),
    value: '0'
  },
  {
    label: t('daily.o1_2'),
    value: '1'
  },
  {
    label: t('daily.o1_3'),
    value: '2'
  }
])

//
const init = () => {
  getShippingList()
  getDictData('project_type')
  getDictData('weather')
  // getDictData('maintenance_daily_ship_location')
  // getCustomerList()
  getlistDockRepairWinningTheBid()

  if (props.type === 'add') {
    setDefault()
  }

  if (['edit', 'add'].includes(props.type)) {
    setRules()
  }

  if (['edit', 'detail'].includes(props.type)) {
    getDetail()
  }
}
</script>

<style scoped lang="scss">
.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.big{
  :deep(*){
    font-size: 16px;
    text-align: center;
  }
}

.border {
  :deep(.el-select-v2__wrapper) {
    border: 0;
    border-bottom: 1px solid #3d3d3d;
    border-radius: 0;
  }
  :deep(.el-input__wrapper) {
    box-shadow: none;
    border-bottom: 1px solid #3d3d3d;
    border-radius: 0;
  }
}

:deep(.el-select-v2__wrapper.is-disabled) {
  background: none;
}
:deep(.el-input.is-disabled .el-input__wrapper) {
  background: none;
}

.el-select-v2 {
  width: 100%;
}

.pro-list {
  .item {
    line-height: 1;
    padding: 8px 20px;
    background: var(--mainColor);
    color: #fff;
    cursor: pointer;
    border-radius: 3px;
    font-size: 12px;
    margin-bottom: 10px;

    &.active {
      background: #252628;
    }
  }
}

.main {
  height: calc(100vh - 380px);
  overflow: auto;
  padding-right: 30px;

  .top {
    width: 500px;
    margin: 0 auto;
  }
}

:deep(.el-date-editor) {
  --el-date-editor-width: 100%;
  .el-input__wrapper {
    width: 100%;
  }
}

:deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: 100px;
}
:deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 100px;
}

.Uploads {
  width: 100%;
}
:deep(.el-upload-list) {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;

  .el-upload-list__item,
  .el-upload--picture-card {
    width: 100%;
    height: 300px;
  }
}

.list {
  .item {
    background: #f5f5f5;
    padding: 20px 10px 10px;
  }
}
</style>
